﻿using System;
using System.Linq;
using System.Reflection;
using Common;
using Common.ConfigModel;
using Microsoft.Extensions.DependencyInjection;

namespace Extensions.Services;

public static class AddAutoMapper
{
    /// <summary>
    /// 添加automapper
    /// </summary>
    /// <param name="service"></param>
    /// <param name="type">automapper 配置类命名空间下的一个类型</param>
    /// <returns></returns>
    /// <exception cref="ArgumentNullException"></exception>
    public static IServiceCollection AddAutoMapperSetup(this IServiceCollection service, Assembly[]? assemblies)
    {
        if (service == null) throw new ArgumentNullException(nameof(service));
        ArgumentNullException.ThrowIfNull(assemblies);
        service.AddAutoMapper(assemblies);
        return service;
    }

    /// <summary>
    /// 从配置文件读取配置
    /// </summary>
    /// <param name="service"></param>
    /// <returns></returns>
    /// <exception cref="ArgumentNullException"></exception>
    public static IServiceCollection AddAutoMapperSetup(this IServiceCollection service)
    {
        if (service == null) throw new ArgumentNullException(nameof(service));
        var config = Appsettings.app<Startup>("Startup");
        if (config==null || string.IsNullOrWhiteSpace(config.AutoMapper))
        {
            throw new Exception("automapper 配置有误 请检查配置文件");
        }

        service.AddAutoMapper(Assembly.Load(config.AutoMapper));
        return service;
    }
}